<!DOCTYPE html>
<html lang="en-US">
  <head>
    <link href="/assets/index.css" rel="stylesheet" type="text/css" />
    <script crossorigin="anonymous" src="/test-harness.js"></script>
    <script crossorigin="anonymous" src="/test-page-object.js"></script>
    <script crossorigin="anonymous" src="/__dist__/webchat-es5.js"></script>
  </head>
  <body>
    <main id="webchat"></main>
    <script>
      run(async function () {
        const { authorizationToken, region } = await fetch(
          'https://hawo-mockbot4-token-app.blueriver-ce85e8f0.westus.azurecontainerapps.io/api/token/speech',
          {
            method: 'POST'
          }
        ).then(res => res.json());

        const riffWavArrayBuffer = await fetch('/assets/hello-world.wav').then(res => res.arrayBuffer());

        const webSpeechPonyfillFactory = WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
          audioConfig: testHelpers.createAudioInputStreamFromRiffWavArrayBuffer(riffWavArrayBuffer),
          credentials: {
            authorizationToken,
            region
          }
        });

        let numResumeAudioContextCalled = 0;

        // GIVEN: Using custom AudioConfig with pre-recorded speech of "Hello, World!".
        WebChat.renderWebChat(
          {
            directLine: WebChat.createDirectLine({ token: await testHelpers.token.fetchDirectLineToken() }),
            store: testHelpers.createStore(),
            webSpeechPonyfillFactory: () => {
              return {
                ...webSpeechPonyfillFactory(),
                resumeAudioContext: () => {
                  numResumeAudioContextCalled++;
                }
              };
            }
          },
          document.getElementById('webchat')
        );

        await pageConditions.uiConnected();

        // WHEN: Microphone button is clicked, it should send out the pre-recorded speech of "Hello, World!"
        await host.click(pageElements.microphoneButton());

        // THEN: resumeAudioContext() should be called once.
        expect(numResumeAudioContextCalled).toBe(1);

        // THEN: It should send out the voice.
        await pageConditions.became(
          'Recognize and send "Hello world."',
          () =>
            /hello\sworld/iu.test(
              pageElements.activities()[0]?.querySelector('[aria-roledescription="message"]')?.innerText || ''
            ),
          5000
        );

        // THEN: The bot should respond.
        await pageConditions.numActivitiesShown(2);

        await host.snapshot();
      });
    </script>
  </body>
</html>
